package com.ztgf.search.scheduled;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.vo.CommodityEsVO;
import com.ztgf.common.constant.Result;
import com.ztgf.search.models.dto.EsGoodsDTO;
import com.ztgf.search.models.dto.EsShopDTO;
import com.ztgf.search.models.service.IShopSearchService;
import com.ztgf.search.models.service.SearchService;
import com.ztgf.search.models.vo.SynchronizationVo;
import com.ztgf.search.server.service.ElasticsearchServiceImpl;
import com.ztgf.search.server.service.ShopSearchServiceImpl;
import com.ztgf.search.server.utils.CollectionHelp;
import com.ztgf.search.server.utils.StringHelper;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static com.ztgf.common.utils.UtilConstants.isNull;


/**
 * @Description ：
 * @Author ： 解风
 * @Date ： 2018/01/26 14:10
 */
@Component
@Slf4j
public class ScheduledTimes {
    @DubboReference
    private ICommodityInfoService commodityInfoService;
    @Resource
    private ElasticsearchServiceImpl elasticsearchService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private IShopSearchService shopSearchService;
    @DubboReference
    private SearchService searchService;
    @Qualifier("restHighLevelClient")
    @Autowired
    public RestHighLevelClient client;


    private String index;

    private String type;

    private String id;

    /**
     * 每天24点执行一次 做一次es更新
     */
    @Scheduled(cron="0 59 23 * * ?")
    public void updateEsGoods() throws Exception{
        log.info("--------------定时任务：每天24点执行一次 做一次es更新 ------------------店铺删除");
        try {
            //检查店铺是否存在
            boolean b = shopSearchService.checkIndex("index_shop_2020");
            if(b){
                shopSearchService.add();
            }

            //检查商品索引是否存在
            boolean b2 = searchService.checkIndex("index_goods_2020");
            if(b2){
                synAllGoods(0);
            }
        }catch (Exception e){
            log.error("同步es数据", e);
        }
    }


    private void synAllGoods(long offset){
        //查询出数据库中的商品进行封装
        List<CommodityEsVO> list = commodityInfoService.queryAllESGoods(offset);
        log.info("ESlist----------------------"+list.size());
        if (isNull(list)) {
            log.error("定时任务：凌晨同步es数据：查询商品为空");
        }else{
            List<EsGoodsDTO> goodsList = new ArrayList<>();
            for (CommodityEsVO vo : list) {
                EsGoodsDTO goodsDTO = new EsGoodsDTO();
                goodsDTO.setId(vo.getId());
                goodsDTO.setLogUrl(vo.getLogUrl());
                goodsDTO.setGoodsName(vo.getGoodsName());
                goodsDTO.setGoodsNameIkSmart(vo.getGoodsName());
                goodsDTO.setGoodsNameIkMaxWord(vo.getGoodsName());
                goodsDTO.setDescription(vo.getDescription());
                goodsDTO.setPrice(vo.getPrice().doubleValue());
                goodsDTO.setOriginalPrice(vo.getOriginalPrice().doubleValue());
                goodsDTO.setPayUserNum(vo.getPayUserNum());
                goodsDTO.setSellerShopId(vo.getSellerShopId());
                goodsDTO.setSellerShopName(vo.getSellerShopName());
                goodsDTO.setSellerShopAddress(vo.getSellerShopAddress());
                goodsDTO.setBrandId(vo.getBrandId().toString());
                goodsDTO.setBrandName(vo.getBrandName());
                goodsDTO.setBrandNameIkSmart(vo.getBrandName());
                goodsDTO.setBrandNameIkMaxWord(vo.getBrandName());
                goodsDTO.setCategoryId(vo.getCategoryId());
                goodsDTO.setCategoryName(vo.getCategoryName());
                goodsDTO.setIsNew(vo.getIsNew());
                goodsDTO.setPopularity(vo.getPopularity());
                goodsDTO.setEvaluationNum(vo.getEvaluationNum());
                goodsDTO.setCreateTime(vo.getCreateTime());
                goodsDTO.setParentCategoryId(vo.getParentCategoryId());
                goodsDTO.setFirstCategoryId(vo.getFirstCategoryId());
                goodsDTO.setFilterIds(vo.getFilterIds());
                goodsDTO.setFilterNames(vo.getFilterNames());
                if (StringHelper.isNotEmpty(vo.getFilterNames())) {
                    String[] split = vo.getFilterNames().split(",");
                    goodsDTO.setFilterName(split);
                }
                if (StringHelper.isNotEmpty(vo.getLabelIds())) {
                    String[] split = vo.getLabelIds().split(",");
                    goodsDTO.setLabelIds(split);
                }
                goodsDTO.setIsXun(vo.getIsXun());
                goodsDTO.setBrowseAmount(vo.getBrowseAmount());
                goodsList.add(goodsDTO);
            }
            log.info("定时任务-------------goodsList=="+goodsList.size());
            searchService.addGoods("index_goods_2020", "goods", 0, goodsList.size(), goodsList);
            synAllGoods(offset + goodsList.size());
        }
    }

}
